package com.mobilesales.android.util;

import java.util.ArrayList;
import java.util.List;

import android.widget.ArrayAdapter;
import android.widget.Filter;

public class CustomFilter<T> extends Filter {

	protected ArrayAdapter<T> adapter;
	protected List<T> items;
	
	
	public CustomFilter(ArrayAdapter<T> adapter, List<T> items) {
		this.adapter = adapter;
		this.items = items;
	}

	
	@Override
	protected FilterResults performFiltering(CharSequence query) {
		FilterResults results = new FilterResults();
		if (query != null && query.toString().length() > 0) {
			List<T> found = new ArrayList<T>();
			for (int i = 0; i < items.size(); i++) {
				T item = items.get(i);
				if (fits(query.toString(), item)) {
					found.add(item);
				}
			}

			results.values = found;
			results.count = found.size();
		} else {
			synchronized (items) {
				results.values = items;
				results.count = items.size();
			}
		}
		return results;
	}

	protected boolean fits(String query, T item) {
		if (item.toString().toLowerCase().contains(query.toLowerCase())) 
			return true;
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void publishResults(CharSequence constraint, FilterResults results) {
		adapter.notifyDataSetChanged();
		adapter.clear();
		List<T> items = (List<T>) results.values;
		for (T item : items)
			adapter.add(item);
	}

}
